/*
Copyright (c) 2009, Young Digital Planet SA
All rights reserved.

* Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this 
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, 
  this list of conditions and the following disclaimer in the documentation 
  and/or other materials provided with the distribution.
* Neither the name of the Young Digital Planet SA nor the names of its 
  contributors may be used to endorse or promote products derived from this 
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
package pl.ydp.jobs.basic
{
	import flash.errors.IllegalOperationError;
	import flash.events.Event;
	
	import pl.ydp.events.PropertyChangeEvent;
	
	import pl.ydp.jobs.IJobInfo;
	import pl.ydp.jobs.YJobs;
	import pl.ydp.jobs.events.DoneEvent;
	import pl.ydp.jobs.events.JobForkEvent;

	/**
	 * Event dispatched when job started.  
	 * 
	 * @eventType pl.ydp.jobs.YJobs.JOB_STARTED
	 */
	[Event(name="jobStarted",type="flash.events.Event")]
	/**
	 * Event dispatched when work is done
	 * 
	 * @eventType pl.ydp.jobs.YJobs.JOB_DONE
	 */
	[Event(name="jobDone",type="pl.ydp.jobs.events.DoneEvent")]
	/**
	 * Event dispatched when work was cancelled (from world)
	 * 
	 * @eventType pl.ydp.jobs.YJobs.JOB_CANCELLED
	 */
	[Event(name="jobCancelled",type="flash.events.Event")]
	/**
	 * Fired when job part is added to this job.
	 * @see #addPart()
	 * @eventType pl.ydp.jobs.events.JobForkEvent.JOB_ADD_PART
	 */
	[Event(name="jobAddPart",type="pl.ydp.jobs.events.JobForkEvent")]
	/**
	 * Fired when properties allWorked/allTotalWork changed.
	 * 
	 * @eventType mx.events.PropertyChangeEvent.PROPERTY_CHANGE
	 * 
	 * @see pl.ydp.jobs.YJobs#ALL_WORKED
	 * @see pl.ydp.jobs.YJobs#ALL_TOTAL_WORK
	 */
	[Event(name="propertyChange",type="mx.events.PropertyChangeEvent")]
	/**
	 * Default implementation of IJobInfo.
	 */
	public class YJobInfo extends YJobHierarchyItem implements IJobInfo
	{
		private var m_dName:String;
		private var m_id:String;
		private var m_worker:*;
		/**
		 * Worked by this object - without other job parts
		 */
		protected var m_internalWorked:int;
		/**
		 * Worked with all hierarchy - this objects and all
		 * sub parts.
		 */
		protected var m_worked:int;
		/**
		 * Total work by this object - without other job parts
		 */
		protected var m_internalTotal:int = YJobs.WORK_UNKNOWN;
		/**
		 * Total work with all hierarchy - this objects and all
		 * sub parts.
		 */
		protected var m_total:int;
		
		private var m_started:Boolean;
		private var m_done:Boolean;
		private var m_cancelled:Boolean;
		
		private var m_parts:Array = [];
		
		/**
		 * Create job informations
		 * @param displayName job display name
		 * @param job job id (look at JOB_ID_SEPARATOR)
		 * @param worker subject of jobs
		 * @see pl.ydp.jobs.YJobs#JOB_ID_SEPARATOR
		 */
		public function YJobInfo( displayName:String, id:String, worker:* = null ) {
			m_dName = displayName;
			m_id = id;
			m_worker = worker;
		}

		/**
		 * @inheritDoc
		 */
		public function get displayName():String {
			return m_dName;
		}
		
		/**
		 * @inheritDoc
		 */
		public function get jobId():String {
			return m_id;
		}
		
		/**
		 * @inheritDoc
		 */
		public function get worker():* {
			return m_worker;
		}
		
		/**
		 * @inheritDoc
		 */
		public function get isStarted():Boolean {
			return m_started;
		}
		
		/**
		 * @inheritDoc
		 */
		public function get isDone():Boolean {
			return m_done;
		}
		
		/**
		 * @inheritDoc
		 */
		// FORKING		
		public function addPart( job:IJobInfo ):void {
			if ( isDone )
				throw new IllegalOperationError( "Can't add job to done job (adding "+job.jobId+" into "+jobId+")" ); 
			m_parts.push( job );
			if ( job.parent==null )
				job.parent = this;
			
			job.addEventListener( PropertyChangeEvent.PROPERTY_CHANGE, childPropertyChanged );
			dispatchEvent( new JobForkEvent(YJobs.JOB_ADD_PART,job) );
			checkRealTotal();
			checkRealWorked();
		}
		
		/**
		 * @inheritDoc
		 */
		public function get jobs():Array {
			return m_parts;
		}
		
		/**
		 * @inheritDoc
		 */
		public function start():void {
			if ( !m_started ) {
				m_started = true;
				dispatchEvent( new Event(YJobs.JOB_STARED) );
			}
		}
		
		public function set totalWork(total:int):void {
			m_internalTotal = total;
			dispatchEvent( PropertyChangeEvent.createUpdateEvent(this,YJobs.ALL_TOTAL_WORK,m_total,(m_total=total)) );
		}
		
		/**
		 * Sets worked by this job instance
		 */  
		public function set worked(worked:int):void {
			m_internalWorked = worked;
			
			checkRealWorked();
		}
		
		/**
		 * Return worked by all jobs in hierarchy
		 */
		public function get allWorked():int {
			return m_worked;
		}
		
		
		/**
		 * Return totalWork by all jobs in hierarchy
		 */
		public function get allTotalWork():int {
			return m_total;
		}
		
		/**
		 * @inheritDoc
		 */
		public function done(success:Boolean=true):void {
			if ( !m_done ) {
				m_done = true;
				dispatchEvent( new DoneEvent(YJobs.JOB_DONE, success) );
			}
		}
		
		/**
		 * @inheritDoc
		 */
		public function step(step:uint=1):void {
			worked = m_internalWorked+step;
		}
		
		/**
		 * @inheritDoc
		 */
		public function cancel():void {
			if ( !m_cancelled ) {
				m_cancelled = true;
				dispatchEvent( new Event(YJobs.JOB_CANCELLED) );
			}
		}
		
		/**
		 * @inheritDoc
		 */
		public function get isCancelled():Boolean {
			return m_cancelled;
		}
		
		/**
		 * Receivers event about change in children worked, totalWork property
		 * and recalculates own properties.
		 * @see #checkRealWorked()
		 */
		protected function childPropertyChanged( evt:PropertyChangeEvent ):void {
			if ( evt.property==YJobs.ALL_WORKED || evt.property==YJobs.ALL_TOTAL_WORK )
				checkRealWorked();
		}
		
		/**
		 * Recalculates worked property from childre. If change is detected
		 * dispatches event.
		 */ 
		protected function checkRealWorked():void {
			var current:Number = m_worked;
			
			for each( var xsub:* in m_parts ) {
				var sub:IJobInfo = IJobInfo(xsub);
				
				if ( sub.allWorked>0 )
					current += sub.allWorked;
			}
			
			var iCurrent:int = int(current);
			if ( m_worked!=iCurrent )
				dispatchEvent( PropertyChangeEvent.createUpdateEvent(this,YJobs.ALL_WORKED,m_worked,(m_worked=iCurrent)) );
		}
		
		/**
		 * Recalculates totalWork property from childre. If change is detected
		 * dispatches event.
		 */ 
		protected function checkRealTotal():void {
			var current:Number = m_total;
			
			if ( current!=-1 ) {
				for each( var xsub:* in m_parts ) {
					var sub:IJobInfo = IJobInfo(xsub);
					
					if ( sub.allTotalWork>0 )
						current += sub.allTotalWork;
					else {
						// if event some part has unknown work, all is doomed
						current = -1;
						break;
					}
				}
			}
			
			var iCurrent:int = int(current);
			if ( m_total!=iCurrent )
				dispatchEvent( PropertyChangeEvent.createUpdateEvent(this,YJobs.ALL_TOTAL_WORK,m_total,(m_total=iCurrent)) );
		}
	}
}